import React, { PureComponent, Fragment } from 'react';
import { Row, Col, Card, Calendar } from 'antd';
import { formatMessage, connect } from 'umi';
import moment from 'moment';
// import { get as _get } from 'object-path';
import uniqueid from 'lodash.uniqueid';
import cn from 'classnames';
import clone from 'lodash/clone';

import { Link }  from 'umi';

import xss from 'xss';
import { dateConversion, dateConversion2 } from '@/utils/utils';

import img3 from '@/assets/data_icon_celebrate_default.png';
import styles from './AttendanceMonth.less';

@connect(({ log, loading }) => ({
    log,
    loading: loading.log
}))
class AttendanceMonth extends PureComponent {
    constructor(props) {
        super(props);
        const { thisMonth, employeeCode, companyid, random } = this.props;
        this.state = {
            value: moment(),
            // selectedValue: moment(),
            thisMonth,
            employeeCode,
            companyid,
            random,
            isInit: true,
            today: {
                leave: [],
                exception: [],
                myOverTime: [],
                myOutTimeVos: [],
                myTripTimeVos: [],
                myAttendanceRecordVos: [],
                holiday: []
            }
        };
    }

    componentDidMount() {
        this.getMonth();
    }

    componentWillReceiveProps(nextProps) {
        const { thisMonth, employeeCode, companyid, random } = this.state;
        // 任何时候props.mode.
        if (
            nextProps.thisMonth !== thisMonth ||
            nextProps.employeeCode !== employeeCode ||
            nextProps.companyid !== companyid ||
            nextProps.random !== random
        ) {
            this.setState(
                {
                    thisMonth: nextProps.thisMonth,
                    employeeCode: nextProps.employeeCode,
                    companyid: nextProps.companyid,
                    random: nextProps.random
                },
                () => {
                    this.getMonth();
                    this.setState({
                        value: moment(`${nextProps.thisMonth}-01`)
                    });
                }
            );
        }
    }

    onSelect = value => {
        const { thisMonth } = this.state;
        if (thisMonth === moment(value).format('YYYY-MM')) {
            this.setState(
                {
                    value
                    // selectedValue: value
                },
                () => {
                    this.getToDay(moment(value).format('YYYY-MM-DD'));
                }
            );
        }
    };

    onPanelChange = value => {
        const { thisMonth } = this.state;
        if (thisMonth === moment(value).format('YYYY-MM')) {
            this.setState({ value });
        }
    };

    /**
     * 组件加载时获取当月事件
     * @method Post
     * @param {string} date 日期
     */
    getMonth = () => {
        const { dispatch } = this.props;
        // const user = JSON.parse(localStorage.getItem('user'));
        const { thisMonth, isInit, employeeCode, companyid } = this.state;
        const parameter = {
            companyCode: companyid,
            employeeCode,
            dayType: 2,
            leaveCode: [''],
            startTime: moment(moment(thisMonth).startOf('year')).format('YYYY-MM-DD'),
            endTime: moment(moment(thisMonth).endOf('year')).format('YYYY-MM-DD'),
            whichYear: moment(thisMonth).format('YYYY'),
            attandanceType: 123,
            typeCode: '',
            outTripOverStatus: ''
        };
        dispatch({
            type: employeeCode ? 'log/fetchMyMonthCalendar' : 'log/fetchMycalendar',
            payload: {
                parameter
            }
        }).then(() => {
            // 判断是否是第一次加载.如果是的话,获取当天日期的事件,如果不是的话,获取选择的当月第一天
            if (isInit) {
                this.getToDay(moment().format('YYYY-MM-DD'));
                this.setState({
                    isInit: false
                });
            } else {
                this.getToDay(moment(moment(thisMonth).startOf('month')).format('YYYY-MM-DD'));
            }
        });
    };

    /**
     * 点击考勤日历的某天，获取当天事件
     * @method Post
     * @param {string} date 日期
     */
    getToDay = date => {
        const {
            log: { data }
        } = this.props;
        const leave = (data.leave || []).filter(item => moment(item.timeDetial).format('YYYY-MM-DD') === date);
        const exception = (data.exception || []).filter(item => item.exceptionDate === date);
        const myOverTime = (data.myOverTime || []).filter(item => item.overDate === date);
        const myOutTimeVos = (data.myOutTimeVos || []).filter(item => item.outDate === date);
        const myTripTimeVos = (data.myTripTimeVos || []).filter(item => item.tripDate === date);
        const holiday = (data.holiday || []).filter(item => item.whichDay === date);
        const myAttendanceRecordVos = (data.myAttendanceRecordVos || []).filter(item => item.signDate === date);

        this.setState({
            today: {
                leave,
                exception,
                myOverTime,
                myOutTimeVos,
                myTripTimeVos,
                holiday,
                myAttendanceRecordVos
            }
        });
    };

    // 周末写入
    weekendDateCellRender = value => {
        const { log } = this.props;
        const { weekend } = log.data;

        return weekend.map(item => {
            if (item === moment(value).format('YYYY-MM-DD')) {
                return <div className={styles.weenkend} key={uniqueid('weekend_')} />;
            }
            return null;
        });
    };

    // 法定节假日写入
    holidayDateCellRender = value => {
        const { log } = this.props;
        const { holiday } = log.data;
        return holiday.map(item => {
            if (item.whichDay === moment(value).format('YYYY-MM-DD')) {
                return (
                    <div className={styles.holiday} key={uniqueid('holiday')}>
                        <i className="iconfont iconoa_form_icon_star_default" />
                    </div>
                );
            }
            return null;
        });
    };

    // 补班写入
    fillsClassDateCellRender = value => {
        const { log } = this.props;
        const { fillsClass } = log.data;

        return fillsClass.map(item => {
            if (item === moment(value).format('YYYY-MM-DD')) {
                return (
                    <div className={styles.fillsClass} key={uniqueid('fillsClass_')}>
                        班
                    </div>
                );
            }
            return null;
        });
    };

    // 请假事件写入
    leaveDateCellRender = value => {
        const { log } = this.props;
        const { leave } = log.data;

        return leave.map(item => {
            const particular = ['产假', '陪产假', '婚假', '孩童假', '附加产假', '丧假', '无薪儿童护理假'];
            if (particular.indexOf(item.leaveName) > -1) {
                if (moment(item.timeDetial).format('YYYY-MM-DD') === moment(value).format('YYYY-MM-DD')) {
                    return <div className={cn(styles.leave)} key={uniqueid('leave_')} />;
                }
            } else if (moment(item.timeDetial).format('YYYY-MM-DD') === moment(value).format('YYYY-MM-DD')) {
                return <div className={cn(styles.leave)} key={uniqueid('leave_')} />;
            }

            return null;
        });
    };

    // 公出加班写入
    vosDateCellRender = value => {
        const { log } = this.props;
        const { myOutTimeVos, myOverTime, myTripTimeVos } = log.data;

        return (
            <Fragment>
                {myOutTimeVos.map(item => {
                    if (moment(item.startTime).format('YYYY-MM-DD') === moment(value).format('YYYY-MM-DD')) {
                        return <div className={cn(styles.leave, styles.green)} key={uniqueid('myOutTimeVos_')} />;
                    }
                    return null;
                })}
                {myOverTime.map(item => {
                    if (moment(item.startTime).format('YYYY-MM-DD') === moment(value).format('YYYY-MM-DD')) {
                        return <div className={cn(styles.leave, styles.green)} key={uniqueid('myOutTimeVos_')} />;
                    }
                    return null;
                })}
                {myTripTimeVos.map(item => {
                    if (moment(item.startTime).format('YYYY-MM-DD') === moment(value).format('YYYY-MM-DD')) {
                        return <div className={cn(styles.leave, styles.green)} key={uniqueid('myOutTimeVos_')} />;
                    }
                    return null;
                })}
            </Fragment>
        );
    };

    /**
     * 异常数据进行处理
     * 组员对象进行对比，如果异常类型和名字一致的情况下修改内容值并生成新数组
     */
    exceptionDataProcessing = data => {
        const oldData = clone(data);
        const newArr = [];
        for (let i = 0; i < oldData.length; i += 1) {
            let exist = false;
            for (let d = i + 1; d < oldData.length; d += 1) {
                if (
                    oldData[i].exceptionName === oldData[d].exceptionName &&
                    oldData[i].exceptionDate === oldData[d].exceptionDate
                ) {
                    exist = true;
                    newArr.push({
                        ...oldData[i],
                        exceptionInterval: 3
                    });
                    oldData[d].oneDay = true;
                    oldData[d].exceptionInterval = 3;
                    oldData[d].countNum = 2;
                    break;
                }
            }
            if (!exist) {
                newArr.push({
                    ...oldData[i],
                    oneDay: true
                });
            }
        }
        return newArr.filter(item => item.oneDay);
    };

    // 考勤异常写入
    exceptionDateCellRender = value => {
        const { log } = this.props;
        const { exception } = log.data;
        const exceptionData = this.exceptionDataProcessing(exception);

        return exceptionData.map(item => {
            if (item.exceptionDate === moment(value).format('YYYY-MM-DD')) {
                return <div className={cn(styles.leave, styles.yellow)} key={uniqueid('exception_')} />;
            }
            return null;
        });
    };

    dateCellRender = value => (
        <Fragment>
            {this.weekendDateCellRender(value)}
            {this.holidayDateCellRender(value)}
            {this.fillsClassDateCellRender(value)}
            <div>
                {this.leaveDateCellRender(value)}
                {this.exceptionDateCellRender(value)}
                {this.vosDateCellRender(value)}
            </div>
        </Fragment>
    );

    renderEvent = value => {
        const { today } = this.state;
        const { leave, exception, myOverTime, myOutTimeVos, myTripTimeVos, holiday, myAttendanceRecordVos } = today;
        const exceptionData = this.exceptionDataProcessing(exception);
        if (
            leave.length === 0 &&
            exceptionData.length === 0 &&
            myOverTime.length === 0 &&
            myOutTimeVos.length === 0 &&
            myTripTimeVos.length === 0 &&
            holiday.length === 0 &&
            myAttendanceRecordVos.length === 0
        ) {
            return (
                <div
                    style={{
                        textAlign: 'center',
                        padding: '30px 0'
                    }}
                >
                    <img src={img3} style={{ marginBottom: 10 }} alt="" />
                </div>
            );
        }
        return (
            <div className={styles.event}>
                {holiday.map(item => {
                    if (item.whichDay === value) {
                        return (
                            <div className={styles.list} key={uniqueid('holiday_list_')}>
                                <b>{item.holidayName}</b>
                            </div>
                        );
                    }
                    return null;
                })}
                {/* 签到 */}
                {myAttendanceRecordVos.map(item => {
                    if (item.signInTime) {
                        return (
                            <div className={styles.list} key={uniqueid('mySignInTime_list_')}>
                                <b>签到</b>
                                <span style={{ marginRight: '4px' }}>{moment(item.signInTime).format('HH:mm')}</span>
                                <Link
                                    to={{
                                        pathname: '/personal/portal/attendance/mine/list/attendanceDetail',
                                        query: {
                                            date: moment(item.signDate).format('YYYY-MM')
                                        }
                                    }}
                                >
                                    {formatMessage({
                                        id: 'columns.noticeList.action.detail'
                                    })}
                                </Link>
                            </div>
                        );
                    }

                    return null;
                })}
                {leave.map(item => {
                    const particular = ['产假', '陪产假', '婚假', '孩童假', '附加产假', '丧假', '无薪儿童护理假'];
                    let html = '';
                    if (particular.indexOf(item.leaveName) > -1) {
                        html += item.startTimeStr;
                        // html = moment(item.startTime).format('YYYY.MM.DD');
                        html += '-';
                        html += item.endTimeStr;
                        // html += moment(item.endTime).format('YYYY.MM.DD');
                    } else {
                        html += item.startTimeStr;
                        // html = moment(item.startTime).format('HH:mm');
                        html += '-';
                        html += item.endTimeStr;
                        // html += moment(item.endTime).format('HH:mm');
                    }
                    return (
                        <div className={styles.list} key={uniqueid('leave_list_')}>
                            <b>{item.leaveName}</b>
                            <Link
                                to={{
                                    pathname: '/personal/portal/attendance/mine/holiday',
                                    query: {
                                        date: moment(item.timeDetial).format('YYYY-MM')
                                    }
                                }}
                            >
                                {formatMessage({
                                    id: 'columns.noticeList.action.detail'
                                })}
                            </Link>
                            <div>
                                <span>{dateConversion(item.leaveLong, 8)}</span>
                                <span>{html}</span>
                            </div>
                        </div>
                    );
                })}
                {exceptionData.map(item => {
                    let html = '';
                    if (item.code === 'absence') {
                        html += '<p>';
                        html += '<b>';
                        html += item.exceptionName;
                        html += '</b>';
                        html += '：';
                        html += '<span>';
                        html += item.countNum;
                        html += '次';
                        html += '</span>';
                        html += '</p>';
                    } else if (item.code === 'lackCard') {
                        html += '<p>';
                        html += '<b>';
                        html += item.exceptionName;
                        html += '</b>';
                        html += '：';
                        html += '<span>';

                        html += item.countNum;
                        html += '次';
                        // if (item.exceptionInterval === 3) {
                        //     html += '<br>';
                        //     html += '上班卡，下班卡';
                        // } else if (item.exceptionInterval === 2) {
                        //     html += '<br>';
                        //     html += '下班卡';
                        // } else if (item.exceptionInterval === 1) {
                        //     html += '<br>';
                        //     html += '上班卡';
                        // }
                        html += '</span>';
                        html += '</p>';
                    } else if (
                        item.code === 'lateOne' ||
                        item.code === 'lateTwo' ||
                        item.code === 'earlyOne' ||
                        item.code === 'earlyTwo'
                    ) {
                        html += '<p>';
                        html += '<b>';
                        html += item.exceptionName;
                        html += '</b>';
                        html += '：';
                        html += '<span>';
                        html += item.exceptionName.substring(0, item.exceptionName.length - 1);
                        html += item.minute;
                        html += '分钟';
                        html += '</span>';
                        html += '</p>';
                    }
                    function goPage(newItem) {
                        if (newItem.code === 'absence') {
                            return (
                                <Link
                                    to={{
                                        pathname: '/personal/portal/attendance/mine/abnormal',
                                        query: {
                                            date: moment(newItem.exceptionDate).format('YYYY-MM'),
                                            key: 'absencelist'
                                        }
                                    }}
                                >
                                    {formatMessage({
                                        id: 'columns.noticeList.action.detail'
                                    })}
                                </Link>
                            );
                        }
                        if (newItem.code === 'lackCard') {
                            return (
                                <Link
                                    to={{
                                        pathname: '/personal/portal/attendance/mine/abnormal',
                                        query: {
                                            date: moment(newItem.exceptionDate).format('YYYY-MM'),
                                            key: 'misslist'
                                        }
                                    }}
                                >
                                    {formatMessage({
                                        id: 'columns.noticeList.action.detail'
                                    })}
                                </Link>
                            );
                        }
                        if (
                            newItem.code === 'lateOne' ||
                            newItem.code === 'lateTwo' ||
                            newItem.code === 'earlyOne' ||
                            newItem.code === 'earlyTwo'
                        ) {
                            return (
                                <Link
                                    to={{
                                        pathname: '/personal/portal/attendance/mine/abnormal',
                                        query: {
                                            date: moment(newItem.exceptionDate).format('YYYY-MM'),
                                            key: 'latelist'
                                        }
                                    }}
                                >
                                    {formatMessage({
                                        id: 'columns.noticeList.action.detail'
                                    })}
                                </Link>
                            );
                        }
                        return '';
                    }
                    return (
                        <div className={styles.list} key={uniqueid('exception_list_')}>
                            <div
                                style={{
                                    display: 'inline-block',
                                    verticalAlign: 'top',
                                    marginRight: '5px'
                                }}
                                // eslint-disable-next-line react/no-danger
                                dangerouslySetInnerHTML={{ __html: xss(html) }}
                            />
                            {goPage(item)}
                        </div>
                    );
                })}
                {myOverTime.map(item => (
                    <div className={styles.list} key={uniqueid('myOverTime_list_')}>
                        <b>加班</b>
                        <Link
                            to={{
                                pathname: '/personal/portal/attendance/mine/overList',
                                query: {
                                    date: moment(item.overDate).format('YYYY-MM')
                                }
                            }}
                        >
                            {formatMessage({
                                id: 'columns.noticeList.action.detail'
                            })}
                        </Link>
                        <div>
                            <span>{dateConversion2(item.overLong)}</span>
                            <span>
                                {/* {item.startTimeStr}-{item.endTimeStr} */}
                                {moment(item.startTime).format('HH:mm')}-{moment(item.endTime).format('HH:mm')}
                            </span>
                        </div>
                    </div>
                ))}
                {myOutTimeVos.map(item => (
                    <div className={styles.list} key={uniqueid('myOutTimeVos_list_')}>
                        <b>外出</b>
                        <Link
                            to={{
                                pathname: '/personal/portal/attendance/mine/outList',
                                query: {
                                    date: moment(item.outDate).format('YYYY-MM')
                                }
                            }}
                        >
                            {formatMessage({
                                id: 'columns.noticeList.action.detail'
                            })}
                        </Link>
                        <div>
                            <span>{dateConversion2(item.outLong)}</span>
                            <span>
                                {moment(item.startTime).format('HH:mm')}-{moment(item.endTime).format('HH:mm')}
                            </span>
                        </div>
                    </div>
                ))}
                {myTripTimeVos.map(item => (
                    <div className={styles.list} key={uniqueid('myTripTimeVos_list_')}>
                        <b>出差</b>
                        <Link
                            to={{
                                pathname: '/personal/portal/attendance/mine/tripList',
                                query: {
                                    date: moment(item.tripDate).format('YYYY-MM')
                                }
                            }}
                        >
                            {formatMessage({
                                id: 'columns.noticeList.action.detail'
                            })}
                        </Link>
                        <div>
                            <span>{dateConversion(item.tripLong, 8)}</span>
                            <span>
                                {moment(item.startTime).format('HH:mm')}-{moment(item.endTime).format('HH:mm')}
                            </span>
                        </div>
                    </div>
                ))}
                {/* 签退 */}
                {myAttendanceRecordVos.map(item => {
                    if (item.signOutTime) {
                        return (
                            <div className={styles.list} key={uniqueid('mySignOutTime_list_')}>
                                <b>签退</b>
                                <span style={{ marginRight: '4px' }}>{moment(item.signOutTime).format('HH:mm')}</span>
                                <Link
                                    to={{
                                        pathname: '/personal/portal/attendance/mine/list/attendanceDetail',
                                        query: {
                                            date: moment(item.signDate).format('YYYY-MM')
                                        }
                                    }}
                                >
                                    {formatMessage({
                                        id: 'columns.noticeList.action.detail'
                                    })}
                                </Link>
                            </div>
                        );
                    }
                    return null;
                })}
            </div>
        );
    };

    render() {
        const { value } = this.state;
        return (
            <Card bordered={false} style={{ borderTop: '1px solid #e8e8e8', marginBottom: 12 }}>
                <Row gutter={12}>
                    <Col xl={6} lg={24}>
                        <div className={styles.calendar}>
                            <div className={styles.date}>
                                <div className={styles.data1}>
                                    <p>
                                        {moment(value).format('YYYY')}年{moment(value).format('MM')}月
                                    </p>
                                    <p>{moment(value).format('dddd')}</p>
                                </div>
                                <div className={styles.data2}>
                                    <p>{moment(value).format('DD')}</p>
                                </div>
                            </div>
                            <div className={styles.abnormal}>
                                {this.renderEvent(moment(value).format('YYYY-MM-DD'))}
                            </div>
                        </div>
                    </Col>
                    <Col xl={18} lg={24}>
                        <Calendar
                            className={styles.CalendarComponent}
                            value={value}
                            onSelect={this.onSelect}
                            onPanelChange={this.onPanelChange}
                            fullscreen={false}
                            // monthFullCellRender={this.dateCellRender}
                            // monthCellRender={this.dateCellRender}
                            dateCellRender={this.dateCellRender}
                        />
                    </Col>
                </Row>
            </Card>
        );
    }
}
export default AttendanceMonth;
